<title>选课搜索</title>

<div class="layui-card layadmin-header">
    <div class="layui-breadcrumb" lay-filter="breadcrumb">
        <a lay-href="">主页</a>
        <a><cite>选课</cite></a>
        <a><cite>专业课</cite></a>
    </div>
</div>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header" id="layui-card-header">专业课</div>
                <div class="layui-card-body">
                    <div class="layui-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label">专业</label>
                            <div class="layui-input-inline">
                                <select lay-filter="yearFilter" id="yearFilter" name="yearFilter">
                                    <option value="">默认年级</option>
                                </select>
                            </div>
                            <div class="layui-input-inline">
                                <select lay-filter="specialtyFilter" id="specialtyFilter" name="specialtyFilter">
                                    <option value="">默认专业</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">课程</label>
                            <div class="layui-input-block" id="class-radio">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">教师</label>
                            <div class="layui-input-block" lay-filter="teacher" id="teacher-radio">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">时间</label>
                            <div class="layui-input-block" id="time-radio">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label"></label>
                            <button class="layui-btn" lay-submit lay-filter="submit">确认</button>
                            <button id="refreshBtn" class="layui-btn" lay-submit lay-filter="refresh">重选</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-card">
                <div class="layui-card-header">人数显示</div>
                <div class="layui-card-body" style="height: 500px;">
                    <div class="layui-carousel layadmin-carousel layadmin-dataview">
                        <div style="width: 100%; height:475px" id="LAY-index-dataview">
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="lineBar">
    <a class="layui-btn layui-btn-xs" lay-event="detail">选课页</a>
</script>
<script>
    layui.use(['jquery', 'table', "echarts", "carousel"], function(){
        var $ = layui.$, form = layui.form,
            echarts = layui.echarts, admin = layui.admin,
            view = layui.view;

        var classInfoIndexList = [];    // 课程索引列表
        var classInfoData;              // 存放课程信息
        var radioIdMap = {};            // radio id记录
        var sel_classinfo_list = [];
        var radioId = 0;
        var year_list = [];         // 记录年份列表
        var specialty_list = [];    // 记录专业列表

        var load = layer.load(2);
        $.ajax({
            url: "/uclass/elective/specialtyclass",
            type: 'GET',
            dataType: 'JSON',
            complete: function (result) {
                layer.close(load);
                // 获取课程列表数据
                result = result.responseJSON;
                if (result.status != 200){
                    layer.msg(result.message);
                } else {
                    classInfoData = result.data;
                    afterSuccess();
                    drawPersonNum(classInfoIndexList);
                }
            }
        });

        function afterSuccess() {

            // 清理工作
            $('#class-radio').empty();
            $('#teacher-radio').empty();
            $('#time-radio').empty();
            classInfoIndexList = [];
            radioIdMap = {};
            radioId = 0;

            // 添加数据
            var data = classInfoData;
            var classNameSet = new Set();
            var teacherSet = new Set();
            var timeSet = new Set();

            for(var index in data) {
                var oneClass = data[index];
                var className = oneClass.className;
                classNameSet.add(className);
                var teacher = oneClass.teachers.toString();
                teacherSet.add(teacher);
                var timeList = [];
                oneClass.time.forEach(function (value) {
                    timeList.push(value.description);
                });
                var time = timeList.toString();
                timeSet.add(time);
                classInfoIndexList.push(index);
            }
            if (classNameSet.size == 1) {
                for (var campus of classNameSet) {
                    addRadio("class-radio", "className", campus, true);
                }
            }else {
                for (var campus of classNameSet) {
                    addRadio("class-radio", "className", campus, false);
                }
            }
            if (teacherSet.size == 1) {
                for (var teacher of teacherSet) {
                    addRadio("teacher-radio", "teacher", teacher, true);
                }
            } else {
                for (var teacher of teacherSet) {
                    addRadio("teacher-radio", "teacher", teacher, false);
                }
            }
            if (timeSet.size == 1) {
                for (var time of timeSet) {
                    addRadio("time-radio", "time", time, true);
                }
            } else {
                for (var time of timeSet) {
                    addRadio("time-radio", "time", time, false);
                }
            }
            form.render();
        }

        function addRadio(id, name, value, checked) {
            radioIdMap[value] = "radio-" + radioId++;
            var html = "<input type='radio' lay-filter='filter' name=" + name + " value='" + value + "' title='" + value + "' id='" + radioIdMap[value]  + "'";
            if (checked){
                html += " checked>";
            }else {
                html += ">";
            }
            $('#' + id).append(html);
        }

        // 人数画图
        function drawPersonNum(classinfoIndexs) {
            var classlist = [];
            var limitNums = [];
            var nowNums = [];
            var determineNums = [];
            classinfoIndexs.forEach(function (index) {
                var timeList = [];
                classInfoData[index].time.forEach(function (value) {
                    timeList.push(value.description);
                });
                classlist.push(classInfoData[index].className + "." + classInfoData[index].teachers.toString() + "--" + timeList.toString())
                limitNums.push(classInfoData[index].limitNum);
                nowNums.push(classInfoData[index].nowNum);
                determineNums.push(classInfoData[index].determineNum);
            });

            // 根据数量判断变成折线图还是柱状图
            var type = "line";
            if (classinfoIndexs.length <= 10) {
                type = "bar";
            }

            // 是否有滑动条,以及显示多少数据
            var len = 100;
            var slide = false;
            if (classinfoIndexs.length >= 20) {
                slide = true;
                len = parseInt(20 / classinfoIndexs.length * 100);
            }
            var personData = {
                title: {
                    text: '专业课人数',
                    textAlign: "auto",
                    textStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: "axis",
                    formatter: function(data)
                    {
                        var teacher = data[0].name.split(".")[1].split("--")[0] + "</br>";

                        var timeStart = data[0].name.indexOf("--");
                        var time = data[0].name.substr(timeStart + 2);
                        var timeList = time.split(",");
                        var timeDescription = "";
                        timeList.forEach(function (time) {
                            timeDescription += time + "</br>";
                        });

                        var personDescription = "";
                        data.forEach(function (classData) {
                            personDescription += classData.seriesName + "：" + classData.data + "</br>"
                        });

                        return teacher + timeDescription + personDescription;
                    }
                },
                legend: {
                    type: "scroll",
                    data: ["限选", "已选", "确定"]
                },
                xAxis: [{
                    type: "category",
                    boundaryGap: true,
                    axisLabel : {
                        interval:0,
                        rotate:20,
                        formatter : function(params){
                            var index = params.indexOf("--");
                            var str = params.substr(0, index);
                            if (str.length > 11) {
                                return str.substr(0, 10) + ".."
                            }
                            return str;
                        }

                    },
                    data: classlist
                }],
                yAxis: [{
                    type: "value"
                }],
                series: [{
                    name: "限选",
                    type: type,
                    barMaxWidth:30,
                    smooth: !0,
                    itemStyle: {
                        normal: {
                            areaStyle: {
                                type: "default"
                            }
                        }
                    },
                    data: limitNums
                }, {
                    name: "已选",
                    type: type,
                    barMaxWidth:30,
                    smooth: !0,
                    itemStyle: {
                        normal: {
                            areaStyle: {
                                type: "default"
                            }
                        }
                    },
                    data: nowNums
                },{
                    name: "确定",
                    type: type,
                    barMaxWidth:30,
                    smooth: !0,
                    itemStyle: {
                        normal: {
                            areaStyle: {
                                type: "default"
                            }
                        }
                    },
                    data: determineNums
                }],
                dataZoom:{
                    type: 'slider',
                    show: slide,
                    height:10,//滚动条高度
                    start:0,//滚动条开始位置（共100等份）
                    end: len//结束位置（共100等份）
                }
            };
            var card= document.getElementById('LAY-index-dataview');
            var myChart = echarts.init(card, layui.echartsTheme);
            myChart.setOption(personData);
            myChart.resize();
        }

        // 监听radio
        form.on('radio(filter)', function(data){
            var classNameSet = new Set();
            var teacherSet = new Set();
            var timeSet = new Set();

            var sel_className = $("input[name='className']:checked").val();
            var sel_teacher = $("input[name='teacher']:checked").val();
            var sel_time = $("input[name='time']:checked").val();
            sel_classinfo_list = [];

            for (var index in classInfoData) {
                var oneClass = classInfoData[index];
                if (sel_className == null || sel_className === oneClass.className) {
                    if (sel_teacher == null || sel_teacher === oneClass.teachers.toString()) {
                        var timeList = [];
                        oneClass.time.forEach(function (value) {
                            timeList.push(value.description);
                        });
                        if (sel_time == null || sel_time === timeList.toString()) {
                            sel_classinfo_list.push(index);
                        }
                    }
                }
            }

            sel_classinfo_list.forEach(function (index) {
                classNameSet.add(classInfoData[index].className);
                teacherSet.add(classInfoData[index].teachers.toString());
                var timeList = [];
                classInfoData[index].time.forEach(function (value) {
                    timeList.push(value.description);
                });
                timeSet.add(timeList.toString());
            });

            // 如果只剩下一个，则直接选中
            if (classNameSet.size == 1) {
                for (var className of classNameSet) {
                    $("#" + radioIdMap[className]).attr("checked",true);
                }
            }
            if(teacherSet.size == 1) {
                for(var teacher of teacherSet) {
                    $("#" + radioIdMap[teacher]).attr("checked",true);
                }
            }

            if(timeSet.size == 1) {
                for(var time of timeSet) {
                    $("#" + radioIdMap[time]).attr("checked",true);
                }
            }
            // 把剩余的radio disable
            for (var radioid in radioIdMap) {
                var id = radioIdMap[radioid];
                var value = document.getElementById(id).value;
                var name = document.getElementById(id).name;
                if (name == 'className') {
                    if (!classNameSet.has(value)) {
                        $("#" + radioIdMap[radioid]).attr("disabled",true);
                    }
                }else if (name == 'teacher') {
                    if (!teacherSet.has(value)) {
                        $("#" + radioIdMap[radioid]).attr("disabled",true);
                    }
                }else if (name == 'time') {
                    if (!timeSet.has(value)) {
                        $("#" + radioIdMap[radioid]).attr("disabled",true);
                    }
                }
            }
            form.render();

            // 如果只有一条数据即为选中，显示备注信息
            if (sel_classinfo_list.length === 1) {
                var timeList = classInfoData[sel_classinfo_list[0]].time;
                var remark = "";
                var remarkSet = new Set();
                timeList.forEach(function (data) {
                    remarkSet.add(data.remark);
                });
                remarkSet.forEach(function (data) {
                    remark += data;
                });
                if (remark !== "") {
                    layer.msg("备注：" + remark);
                }
            }
            drawPersonNum(sel_classinfo_list);
        });

        // 监听确认按钮
        form.on("submit(submit)", function (data) {
            if ( sel_classinfo_list.length !== 1) {
                layer.msg("请选择");
                return;
            }
            var data = classInfoData[sel_classinfo_list[0]];
            admin.popup({
                title: "选课",
                area: ["420px", window.screen.availHeight * 0.9 + "px"],
                id: "LAY-popup-user-elective-confirm",
                success: function(layero, index) {
                    data['teacher'] = data['teachers'].toString();
                    var remark = "";
                    var timeList = data.time;
                    layui.each(timeList, function (index, item) {
                        remark += item.description;
                        if(item.classRoom.toString() !== "") {
                            remark += "-" + item.classRoom.toString();
                        }
                        if (item.remark !== "") {
                            remark += "-" + item.remark;
                        }
                        remark += "<br>";
                    });
                    data['remark'] = remark;
                    view(this.id).render("menu/elective/confirmClass", data).done(function () {
                        form.on("submit(LAY-user-back-submit)",function (formData) {
                            layer.close(index);
                            var load = layer.load(2);
                            var field = formData.field;
                            var content = {};
                            content['classCode'] = data.classCode;
                            content['classNum'] = data.classNum;
                            content['coin'] = field['coin'];
                            if (field.hasOwnProperty("buy")) {content['buy'] = true}
                            else {content['buy'] = false};
                            if (field.hasOwnProperty("retake")) {content['retake'] = true}
                            else {content['retake'] = false};
                            if (field.hasOwnProperty("adjust")) {content['adjust'] = true}
                            else {content['adjust'] = false};
                            $.ajax({
                                url: '/uclass/elective/save',
                                type: 'POST',
                                contentType: 'application/json',
                                data: JSON.stringify(content),
                                dataType: 'json',
                                complete: function (result) {
                                    result = result.responseJSON;
                                    if (result.status === 200) {
                                        layer.msg("选课成功");
                                    }else {
                                        layer.msg(result.message);
                                    }
                                    layer.close(load);
                                }
                            })
                        });
                    });
                }
            });
        });

        // 监听重选按钮
        form.on("submit(refresh)", function (data) {
            sel_classinfo_list = [];
            $("input[name='className']:checked").attr("checked", false);
            $("input[name='teacher']:checked").attr("checked", false);
            $("input[name='time']:checked").attr("checked", false)
            for (var radioid in radioIdMap) {
                $("#" + radioIdMap[radioid]).attr("disabled",false);
            }
            var list = [];
            for(var i in classInfoData) {list.push(i)};
            drawPersonNum(list);
            form.render();
        });


        // 渲染年份
        var today = new Date();
        var year = today.getFullYear();
        var startYear = year - 4;
        for (var i = year; i >= startYear; i--) {
            $('#yearFilter').append("<option value='" + i + "'>" + i + "</option>");
            year_list.push(i);
        }
        form.render("select");

        // 监听年份，点击后获取当年的专业列表
        form.on("select(yearFilter)", function (obj) {
            $('#specialtyFilter').empty();
            form.render();
            if (obj.value === "") return;
            var sel_year = obj.value;
            $.ajax({
                url: "/uclass/elective/specialty?year=" + sel_year,
                dataType: 'json',
                complete: function (result) {
                    result = result.responseJSON;
                    if (result.status !== 200) {
                        layer.msg(result.message);
                    }
                    var list = result.data;
                    specialty_list = [];
                    var html = "<option value=''>请选择专业</option>";
                    $('#specialtyFilter').append(html);
                    for(var specialty in list) {
                        specialty = list[specialty];
                        specialty_list.push(specialty);
                        html = "<option value='" + specialty.department_code
                            + " " + specialty.code + "'>" + specialty.name + "</option>"
                        $('#specialtyFilter').append(html);
                    }
                    form.render("select");
                }
            })
        });

        // 监听点击专业
        form.on('select(specialtyFilter)', function (obj) {
            var year = $('#yearFilter').val();
            var specialty_code = $('#specialtyFilter').val().split(' ')[1];
            if(year === "" || specialty_code === ""
                || year === undefined || specialty_code === undefined
                || year === null || specialty_code === null) {
                layer.msg("请选择年份与专业");
                return;
            }
            load = layer.load(2);
            $.ajax({
                url: "/uclass/elective/specialtyclass?grade=" + year + "&code=" + specialty_code,
                type: 'GET',
                dataType: 'JSON',
                complete: function (result) {
                    layer.close(load);
                    // 获取课程列表数据
                    result = result.responseJSON;
                    if (result.status != 200){
                        layer.msg(result.message);
                    } else {
                        classInfoData = result.data;
                        afterSuccess();
                        drawPersonNum(classInfoIndexList);
                    }
                }
            });
        })
    });
</script>